package cn.itcast.nems.product.scheduler;

import cn.itcast.nems.product.dao.dataobject.TuitionFeeDO;
import cn.itcast.nems.product.dao.dataobject.TuitionFeePhaseDO;
import cn.itcast.nems.product.dao.dataobject.TuitionFeeSchoolDO;
import cn.itcast.nems.product.dao.mapper.TuitionFeeMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liyong
 * create: 2023-09-06 16:03:19
 **/
public class BaseDataProcessor {
    private final List<TuitionFeeDO> tuitionFees;
    // key: tuitionFeeId
    private final Map<Integer, List<TuitionFeePhaseDO>> phases;
    // key: tuitionFeeId
    private final Map<Integer, Set<String>> schools;

    public BaseDataProcessor(TuitionFeeMapper tuitionFeeMapper, Set<String> classTypeIds) {
        this.tuitionFees = tuitionFeeMapper.selectTuitionFeesByClassTypeIds(classTypeIds);
        Set<Integer> tuitionIds = tuitionFees.stream().map(TuitionFeeDO::getId).collect(Collectors.toSet());
        this.phases = this.findTuitionFeePhases(tuitionFeeMapper, tuitionIds);
        this.schools = this.findTuitionFeeSchools(tuitionFeeMapper, tuitionIds);
    }

    public BaseDataProcessor(TuitionFeeMapper tuitionFeeMapper) {
        this.tuitionFees = tuitionFeeMapper.selectTuitionFees();
        Set<Integer> tuitionIds = tuitionFees.stream().map(TuitionFeeDO::getId).collect(Collectors.toSet());
        this.phases = this.findTuitionFeePhases(tuitionFeeMapper, tuitionIds);
        this.schools = this.findTuitionFeeSchools(tuitionFeeMapper, tuitionIds);
    }

    public List<TuitionFeeDO> getTuitionFees() {
        return tuitionFees;
    }

    public Map<Integer, List<TuitionFeePhaseDO>> getPhases() {
        return phases;
    }

    public Map<Integer, Set<String>> getSchools() {
        return schools;
    }

    // key: tuitionFeeId
    private Map<Integer, List<TuitionFeePhaseDO>> findTuitionFeePhases(TuitionFeeMapper tuitionFeeMapper, Set<Integer> tuitionFeeIds) {
        final List<TuitionFeePhaseDO> tuitionFeePhases = tuitionFeeMapper.selectTuitionFeePhases(tuitionFeeIds);
        return tuitionFeePhases
                .stream()
                .collect(Collectors.groupingBy(TuitionFeePhaseDO::getTuitionFeeId));
    }

    // key: tuitionFeeId
    private Map<Integer, Set<String>> findTuitionFeeSchools(TuitionFeeMapper tuitionFeeMapper, Set<Integer> tuitionFeeIds) {
        final List<TuitionFeeSchoolDO> tuitionFeeSchools = tuitionFeeMapper.selectTuitionFeeSchools(tuitionFeeIds);
        return tuitionFeeSchools
                .stream()
                .collect(Collectors.groupingBy(TuitionFeeSchoolDO::getTuitionFeeId,
                        HashMap::new,
                        Collectors.mapping(TuitionFeeSchoolDO::getSchoolCode, Collectors.toSet())));
    }
}
